#!/usr/bin/env python
#-*- coding:UTF-8 -*-

import os,shutil,sys
import platform
import zipfile
separator = '/'
sysstr = platform.system()
if(platform.system() =="Windows"):
    separator = '\\'
folder = input('请输入需要转码的文件夹路径:')

def traverse(f):
    fs = os.listdir(f)
    for f1 in fs:
        tmp_path = os.path.join(f,f1)
        if not os.path.isdir(tmp_path):
            if file_extension(tmp_path) == '.zip' :
                transcod_from_zipfile(tmp_path)
        else:
            traverse(tmp_path)

def zip_folder(path):
    zippath = path + ".zip"
    z = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED)
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            z.write(os.path.join(dirpath,filename),filename)
    z.close()

def unzip(path,des):
#    shutil.unpack_archive(folder,des)
    z = zipfile.ZipFile(path, 'r')
    z.extractall(des)
    z.close()

def formattomp4(srcfile,cachefolder):
    filename = srcfile.split(separator)[-1]
    dstfile = os.path.join(cachefolder,filename)
    shutil.move(srcfile,dstfile)
    if(platform.system() =="Windows"):
        comm = 'ffmpeg -i "{0}" -strict -2 "{1}"'.format(dstfile, srcfile)
        os.system(comm)
    else:
        comm = 'ffmpeg -i {0} -strict -2 {1}'.format(dstfile, srcfile)
        os.system(comm)

# 获取文件的扩展名
def file_extension(path):
    splits = os.path.splitext(path)
    return splits[1]
                  
# 创建文件夹
def create_folder(path):
    if os.path.exists(path):
        shutil.rmtree(path)
    os.mkdir(path)

# 转码zip文件
def transcod_from_zipfile(path):
    temppath = os.path.splitext(path)[0]
    unzip(path,temppath)
    fs = os.listdir(temppath)
    tanscodetemppath = temppath + "_tmp"
    create_folder(tanscodetemppath)
    for f1 in fs:
        tmpfilepath = os.path.join(temppath,f1)
        if file_extension(tmpfilepath) == ".mp4" or file_extension(tmpfilepath) == ".MP4":
            formattomp4(tmpfilepath,tanscodetemppath)
    shutil.rmtree(tanscodetemppath)
    os.remove(path)
    zip_folder(temppath)
    shutil.rmtree(temppath)

if __name__ == '__main__':
    traverse(folder)



